package base;

import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.ToString;

import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * 通用返回结果，服务端响应的数据最终都会
 *
 * @param <T>
 */
@Data
@ToString
public class R<T> implements Serializable {

    private Integer code;

    private String msg;

    private T data;

    public R() {
        this.code = 200;
        this.data = null;
        this.msg = "";
    }

    @SneakyThrows
    public void push(HttpServletResponse resp) {
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JSONUtil.toJsonStr(this, JSONConfig.create().setIgnoreNullValue(false)));
    }

    public static <T> R<T> success(T object) {
        R<T> r = new R<T>().setCode(200);
        return object instanceof String ? r.setMsg((String) object) : r.setData(object);
    }

    public static <T> R<T> success() {
        return R.success(null);
    }

    public static <T> R<T> error() {
        return R.error(null);
    }

    public static <T> R<T> error(String msg) {
        return new R<T>().setCode(500).setMsg(msg);
    }

    public static <T> R<T> unAuthorized() {
        return new R<T>().setCode(401);
    }

    public R<T> setCode(Integer code) {
        this.code = code;
        return this;
    }

    public R<T> setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public R<T> setData(T data) {
        this.data = data;
        return this;
    }

}
